package com.zhanghe.study.sqlsession;

import com.zhanghe.study.config.MyConfig;
import com.zhanghe.study.table.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MyExecutor implements Executor {
    private MyConfig config = new MyConfig();
    public <T> T query(String sql, Object parameter) {
        Connection connection = getConnection();
        ResultSet set = null;
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,parameter.toString());
            set = preparedStatement.executeQuery();
            User user = new User();
            while(set.next()){
                user.setId(set.getString("id"));
                user.setName(set.getString("name"));
                user.setSex(set.getString("sex"));
            }
            return (T) user;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try{
                if(set != null){
                    set.close();
                }
                if (preparedStatement != null){
                    preparedStatement.close();
                }
                if(connection != null){
                    connection.close();
                }
            } catch (Exception e){
                e.printStackTrace();
            }

        }
        return null;
    }

    private Connection getConnection(){
        Connection connection = config.build("config.xml");
        return connection;
    }
}
